<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>药品信息</h3>
      <el-form ref="drug" :model="drug" status-icon label-position="left" label-width="100px"
               style="width: 800px; margin-left:50px;">
        <el-row>
          <el-col :span="24">
            <el-form-item label="药品编号">
              {{drug.code}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="药品名称">
              {{ drug.name }}
              <el-link type="primary" v-permission="['POST /admin/drug/update']" icon="el-icon-edit"
                       @click="handleDrugEdit"></el-link>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="药品规格">
              {{ drug.spec }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="本位码">
              {{ drug.standardCode }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批准文号">
              {{ drug.approvalCode }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别限制">
              <el-tag v-if="drug.genderRestrict == 1">限男性</el-tag>
              <el-tag type="danger" v-else-if="drug.genderRestrict == 2">限女性</el-tag>
              <el-tag type="success" v-else>不限</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="儿童用药">
              <el-tag type="danger" v-if="drug.childrenFlag">是</el-tag>
              <el-tag type="success" v-else>否</el-tag>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="剂量单位">
              {{ drug.dosageUnit }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产厂家">
              {{ drug.factory }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="box-card">
      <div class="op-create">
        <h3>药品用法</h3>
        <div>
          <el-button type="primary" @click="handleCreate">添加</el-button>
        </div>
      </div>
      <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
        <el-table-column align="center" label="ID" prop="id" sortable/>

        <el-table-column align="left" label="用法" prop="usage"/>
        <el-table-column align="left" label="用量">
          <template slot-scope="scope">
            {{ scope.row.dosage + ' ' + scope.row.dosageUnit }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="频率" prop="frequency"/>
        <el-table-column align="left" label="性别">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.genderRestrict == 1">限男性</el-tag>
            <el-tag type="danger" v-else-if="scope.row.genderRestrict == 2">限女性</el-tag>
            <el-tag type="success" v-else>不限</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="left" label="年龄">
          <template slot-scope="scope">
            {{ getAgeRang(scope.row.ageStart, scope.row.ageEnd) }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="权重" prop="weight" sortable/>

        <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button v-permission="['POST /admin/drug/usage/update']" type="primary" size="mini"
                       @click="handleUpdate(scope.row)">编辑
            </el-button>
            <el-button v-permission="['POST /admin/drug/usage/delete']" type="danger" size="mini"
                       @click="handleDelete(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                  @pagination="getList"/>

      <!-- 添加或修改对话框 -->
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="800px">
        <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px"
                 style="width: 700px; margin-left:50px;">
          <el-form-item label="用法" prop="usage">
            <el-input v-model="dataForm.usage"/>
          </el-form-item>
          <el-form-item label="用量" prop="dosage">
            <el-input v-model="dataForm.dosage"/>
          </el-form-item>
          <el-form-item label="剂量单位" prop="dosageUnit">
            <el-input v-model="dataForm.dosageUnit"/>
          </el-form-item>
          <el-form-item label="频率" prop="frequency">
            <el-input v-model="dataForm.frequency"/>
          </el-form-item>

          <el-form-item label="性别限制" prop="genderRestrict">
            <el-radio-group v-model="drug.genderRestrict">
              <el-radio :label="0">不限</el-radio>
              <el-radio :label="1">限男性</el-radio>
              <el-radio :label="2">限女性</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="适用年龄">
            <el-slider
              v-model="ages"
              range
              show-stops
              :marks="ageMark"
              :min="0"
              :max="150"
              @change="handleChange">
            </el-slider>
          </el-form-item>

          <el-form-item label="权重" prop="weight">
            <el-input v-model="dataForm.weight"/>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
          <el-button v-else type="primary" @click="updateData">确定</el-button>
        </div>
      </el-dialog>

    </el-card>

    <el-card class="box-card" v-permission="['GET /admin/drug/usage/listDiag']">
      <div class="op-create">
        <h3>用药诊断</h3>
      </div>
      <!-- 查询结果 -->
      <el-table v-loading="listLoadingDiag" :data="listDiag" element-loading-text="正在查询中。。。" border fit
                highlight-current-row>
        <el-table-column align="center" label="ID" prop="id" sortable width="120"/>

        <el-table-column align="left" label="编码" prop="diagnosis.code" width="180"/>
        <el-table-column align="left" label="诊断名称" prop="diagnosis.name"/>
        <el-table-column align="left" label="标准编码" prop="diagnosis.standardCode" width="140"/>
        <el-table-column align="left" label="权重" prop="weight" width="120"/>
        <el-table-column align="left" label="性别限制" width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.diagnosis.genderRestrict == 1">限男性</el-tag>
            <el-tag type="danger" v-else-if="scope.row.diagnosis.genderRestrict == 2">限女性</el-tag>
            <el-tag type="success" v-else>不限</el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" class-name="small-padding fixed-width" width="220">
          <template slot-scope="scope">
            <el-button v-permission="['POSt /admin/drug/usage/delDiag']" type="danger" size="mini"
                       @click="handleDeleteDiag(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="totalDiag > 0" :total="totalDiag" :page.sync="listQueryDiag.page"
                  :limit.sync="listQueryDiag.limit"
                  @pagination="getListDiag"/>

    </el-card>
  </div>
</template>

<script>
  import {readDrug} from "@/api/drug"
  import {listUsage, readUsage, createUsage, updateUsage, deleteUsage, listDiag, deleteDiag} from "@/api/drugUsage"
  import Pagination from '@/components/Pagination'

  export default {
    name: "DrugUsage",
    components: {Pagination},
    data() {
      return {
        drug: {
          id: undefined,
          code: '',
          name: '',
          spec: '',
          standardCode: '',
          approvalCode: '',
          genderRestrict: 0,
          childrenFlag: false,
          dosageUnit: '',
          factory: ''
        },
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          drugId: undefined,
          sort: 'weight',
          order: 'desc',
        },
        listDiag: null,
        totalDiag: 0,
        listLoadingDiag: true,
        listQueryDiag: {
          page: 1,
          limit: 20,
          drugId: undefined,
          sort: 'weight',
          order: 'desc',
        },
        dataForm: {
          id: undefined,
          usage: undefined,
          dosage: undefined,
          frequency: undefined,
          genderRestrict: 0,
          ageStart: null,
          ageEnd: null,
          drugId: undefined,
          dosageUnit: undefined,
          weight: 1,
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        ages: [],
        ageMark: {
          0: '0岁',
          12: '12岁',
          20: '20岁',
          30: '30岁',
          40: '40岁',
          50: '50岁',
          60: '60岁',
          70: '70岁',
          80: '80岁',
          90: '90岁',
          100: '100岁',
        },
        rules: {
          usage: [
            {required: true, message: '用法不能为空', trigger: 'blur'}
          ],
        },
      }
    },
    created() {
      this.init()
    },
    methods: {
      init() {
        if (this.$route.query.id == null) {
          return
        }

        const drugId = this.$route.query.id
        this.listQuery.drugId = drugId
        this.listQueryDiag.drugId = drugId

        readDrug({id: drugId}).then(response => {
          this.drug = response.data.data
          this.getList()
          this.getListDiag()
        }).catch()
      },
      getList() {
        this.listLoading = true
        listUsage(this.listQuery)
          .then(response => {
            this.list = response.data.data.list
            this.total = response.data.data.total
            this.listLoading = false
          })
          .catch(() => {
            this.list = []
            this.total = 0
            this.listLoading = false
          })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      resetForm() {
        this.dataForm = {
          id: undefined,
          drugId: this.drug.id,
          dosageUnit: this.drug.dosageUnit,
          genderRestrict: 0,
          ageStart: 0,
          ageEnd: 150,
          weight: 1,
        }
      },
      handleChange(val) {
        this.dataForm.ageStart = val[0]
        this.dataForm.ageEnd = val[1]
      },
      handleCreate() {
        this.resetForm()
        this.ages = [this.dataForm.ageStart, this.dataForm.ageEnd]
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            createUsage(this.dataForm)
              .then(response => {
                this.list.unshift(response.data.data)
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '添加药品用法成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },
      handleUpdate(row) {
        this.dataForm = Object.assign({}, row)
        if (!this.dataForm.ageStart) {
          this.dataForm.ageStart = 0
        }

        if (!this.dataForm.ageEnd) {
          this.dataForm.ageEnd = 150
        }

        this.ages = [this.dataForm.ageStart, this.dataForm.ageEnd]

        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            updateUsage(this.dataForm)
              .then(() => {
                for (const v of this.list) {
                  if (v.id === this.dataForm.id) {
                    const index = this.list.indexOf(v)
                    this.list.splice(index, 1, this.dataForm)
                    break
                  }
                }
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新药品用法成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },
      handleDelete(row) {
        this.$confirm('删除药品用法, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteUsage(row)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '删除药品用法成功'
              })
              this.getList()
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }).catch(() => {

        })
      },
      getAgeRang(start, end) {
        if (start && end) {
          return start + '岁 ~ ' + end + '岁'
        }
        if (start) {
          return start + '岁 起'
        }
        if (end) {
          return '不超过' + end + '岁'
        }

        return ''
      },
      handleDrugEdit() {
        this.$router.push({path: '/drug/edit', query: {id: this.drug.id}})
      },
      getListDiag() {
        this.listLoadingDiag = true
        listDiag(this.listQueryDiag)
          .then(response => {
            this.listDiag = response.data.data.list
            this.totalDiag = response.data.data.total
            this.listLoadingDiag = false
          })
          .catch(() => {
            this.listDiag = []
            this.totalDiag = 0
            this.listLoadingDiag = false
          })
      },
      handleDeleteDiag(row) {
        this.$confirm('删除药品诊断, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteDiag(row)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '删除药品诊断成功'
              })
              this.getListDiag()
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }).catch(() => {

        })
      },
    }
  }
</script>

<style scoped>
  .el-card {
    margin-bottom: 10px;
  }

  .filter-container {
    margin-top: 20px;
  }

  .op-create {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
</style>
